import Taro from '@tarojs/taro'
import {API_COMM_UPLOAD} from '../constants/api'
import {info, warn, error} from './log.js'

const CODE_SUCCESS = 1000
const CODE_AUTH_EXPIRED = '600'

function getStorage(key) {
  return Taro.getStorage({key}).then(res => res.data).catch(() => '')
}

function updateStorage(data = {}) {
  return Promise.all([
    Taro.setStorage({key: 'token', data: data['3rdSession'] || ''}),
    Taro.setStorage({key: 'uid', data: data['uid'] || ''})
  ])
}


/**
 * 简易封装网络请求
 * // NOTE 需要注意 RN 不支持 *StorageSync，此处用 async/await 解决
 * @param {*} options
 */
export default async function fetch(options) {
  const {url, payload, method = 'GET', showToast = true, autoLogin = true} = options
  let {delayTime} = options
  if (!delayTime) {
    delayTime = 0
  }
  let header = {
    'Content-Type': 'application/json;charset=UTF-8'
  }
  // const token = await getStorage('token')
  // const header = token ? { 'WX-PIN-SESSION': token, 'X-WX-3RD-Session': token } : {}
  // if (method === 'POST') {
  //   header['content-type'] = 'application/json'
  // }
  console.log('HOST')
  const token = Taro.getStorageSync('token')
  if (token) {
    header.Authorization = token
  }
  if (url == API_COMM_UPLOAD) {
    header['Content-type'] = 'multipart/form-data'
  }
  return new Promise((resolve, reject) => {
    Taro.request({
      url,
      method,
      data: payload,
      header
    }).then(async (res) => {
      const {statusCode} = res
      if (statusCode == 401) {
        //需要重新登录
        reject(res.data.message)
        Taro.clearStorageSync()
        Taro.navigateTo({
          url: `/pages/auth/index`
        })
        return;
      }
      if (statusCode == 403) {
        //权限失效
        Taro.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 1000
        })
        reject(res.data.message)
        return;
      }
      const {code, data, message} = res.data
      console.log('code', code)
      if (code !== CODE_SUCCESS) {
        warn(`用户状态异常 req:${JSON.stringify(payload)} response:${JSON.stringify(res.data)}`)
        Taro.showToast({
          title: message,
          icon: 'none',
          duration: 1000
        })
        Taro.clearStorageSync()
        reject(message)
        return;
      }

      // if (url === API_USER_LOGIN) {
      //   await updateStorage(data)
      // }

      // XXX 用户信息需展示 uid，但是 uid 是登录接口就返回的，比较蛋疼，暂时糅合在 fetch 中解决
      // if (url === API_USER) {
      //   const uid = await getStorage('uid')
      //   return { ...data, uid }
      // }
      if (delayTime) {
        await delay(delayTime)
        info(`调用接口成功 req:${JSON.stringify(payload)} response:${JSON.stringify(res.data)}`)
        resolve(data)
      } else {
        info(`调用接口成功 req:${JSON.stringify(payload)} response:${JSON.stringify(res.data)}`)
        resolve(data)
      }
    }).catch((err) => {
      error(`调用接口失败 req:${JSON.stringify(payload)} response:${JSON.stringify(err)}`)
      console.log('请求失败', err)
      // const defaultMsg = err.code === CODE_AUTH_EXPIRED ? '登录失效' : '请求异常'
      if (showToast) {
        Taro.showToast({
          title: err.errMsg || err,
          icon: 'error',
          duration: 1000
        })
      }

      // if (err.code === CODE_AUTH_EXPIRED && autoLogin) {
      //   Taro.navigateTo({
      //     url: '/pages/user-login/user-login'
      //   })
      // }
      reject({message: err.errMsg || err, ...err})
    })
  })
}


async function delay(delayTime) {
  await new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, delayTime);
  });
}
